import { Promise, Thenable } from 'es6-promise';

class Base {
    protected host: string;
    private _timeout: number = 300000;

    constructor(host: string) {
        this.host = host;
    }

    set timeout(value: number) {
        this._timeout = value;
    }

    protected post<R1>(url: string, data: any, count: number = 3): Promise<Response<R1>> {
        let timeout = this._timeout;
        let that = this;
        // @ts-ignore
        let token = wx.getStorageSync('accesstoken');
        return new Promise<R1>(function (resolve, reject) {
            let fullUrl = that.host + url + "?service_token=" + token;
            // @ts-ignore
            let success = function (res: wx.DataResponse) {
                if (res.data.code === 403 || res.data.code === 401) {
                    console.log('token过期，需要重新登录');
                }
                resolve(res.data);
            };
            // @ts-ignore
            let fail = function (res: wx.DataResponse) {
                console.error(res);
                reject(res);
            }
            // @ts-ignore
            wx.request({
                url: fullUrl,
                data: data || '',
                header: {
                    'content-type': 'application/json',
                    'Accept': 'application/json'
                },
                method: 'POST',
                dataType: 'json',
                responseType: 'text',
                timeout: timeout,
                success: success,
                fail: fail,
            })
        }).catch((error) => {
            if (count > 0) {
                return this.post<R1>(url, data, count - 1);
            } else {
                return Promise.reject(error);
            }
        });
    }

    protected get<R1>(url: string, count: number = 3): Promise<Response<R1>> {
        let timeout = this._timeout;
        // @ts-ignore
        let token = wx.getStorageSync('accesstoken');
        let that = this;
        return new Promise<R1>(function (resolve: (value?: R1 | Thenable<R1>) => void, reject: (error?: any) => void) {
            let fullUrl = that.host + url + "?service_token=" + token;
            // @ts-ignore
            let success = function (res: wx.DataResponse) {
                if (res.data.code === 403 || res.data.code === 401) {
                    that.login().finally(reject);
                } else {
                    resolve(res.data);
                }
            };
            // @ts-ignore
            let fail = function (res: wx.DataResponse) {
                console.error(res);
                reject(res);
            }
            // @ts-ignore
            wx.request({
                url: fullUrl,
                header: {
                    'content-type': 'application/json',
                    'Accept': 'application/json'
                },
                method: 'GET',
                dataType: 'json',
                responseType: 'text',
                timeout: timeout,
                success: success,
                fail: fail,
            })
        }).catch((error) => {
            if (count > 0) {
                return this.get<R1>(url, count - 1);
            } else {
                return Promise.reject(error);
            }
        });
    }

    protected login(): Promise<string> {
        return new Promise<string>(function (resolve, reject) {
            // @ts-ignore
            let success = function (res: wx.LoginResponse) {
                resolve(res.code);
            }
            // @ts-ignore
            wx.login({
                success: success,
                fail: reject
            })
        });
    }

    public refreshToken(): Promise<string> {
        // @ts-ignore
        let appid = wx.getAccountInfoSync().miniProgram.appId;
        let host = this.host;
        let timeout = this.timeout;
        return this.login().then(function (code) {
            let url = host + '/user/login/' + appid + '/' + code;
            return new Promise<string>(function (resolve, reject) {
                // @ts-ignore
                let success = function (res: wx.DataResponse) {
                    if (res.data.code === 200) {
                        // @ts-ignore
                        wx.setStorageSync('accesstoken', res.data.data.token);
                        resolve(res.data.data.token);
                    } else {
                        reject(res);
                    }
                }
                // @ts-ignore
                wx.request({
                    url: url,
                    method: 'POST',
                    header: {
                        'content-type': 'application/json'
                    },
                    timeout: timeout,
                    success: success,
                    fail: reject
                })
            });
        });
    }
}

interface Response<R> {
    success: boolean,
    code: number,
    message: string,
    data: R
}

/***贴在下面==================================================vvvvvvvvvvvvvv====================**/
/**  */
interface app_westore_api_support_LoginInfo {
    /**  */
    token: any
    /**  */
    userid: any
    /**  */
    openid: any
    /**  */
    cusid: any
    /**  */
    storeid: any
}

/** 会员申请 */
interface app_westore_api_vo_MemberApplyRequest {
    /** 会员名称 */
    name: string
    /** 手机号 */
    mobile: string
    /** 公司 */
    company_name: string
}

/**  */
interface app_westore_api_vo_MemberApplyResult {
    /** 会员申请结果:1:待审核；2:已通过,3:未通过 */
    status: number
}

/**  */
interface app_westore_api_vo_MyCustomerResult {
    /** 会员ID */
    id: number
    /** 会员名称 */
    nickname: string
    /** 会员头像 */
    avator: string
    /** 会员手机号码 */
    mobile: string
    /** 1:男,2:女,0:未知 */
    gender: number
    /** 所在城市 */
    city: string
    /** 所在省 */
    province: string
}

/**  */
interface app_westore_api_vo_WestoreInfoResult {
    /** 会员申请状态:1:开启2:关闭 */
    apply_status: number
    /** 客服电话 */
    mobile: number
}

/**  */
interface app_westore_api_vo_PriceIntervalResult {
    /** 价格开始值 */
    start: number
    /** 价格结束值 */
    end: number
}

/**  */
interface app_westore_api_vo_SearchPriceGoodsResult {
    /** 商品ID */
    id: number
    /** 商品名称 */
    name: string
    /** 一级分类(点礼企服) */
    first_category: number
    /** 二级分类 */
    second_category: number
    /** 价格 */
    price: number
    /** 品牌名称 */
    brand: string
    /** 原图 */
    pic: string
    /** 200*200图片 */
    pic_sml: string
    /** 配送范围 */
    range: string
    /** 配送省份 */
    province: string
    /** 产品明细 */
    intro: string
    /** 结算价格 */
    sprice: number
    /** 阶梯运费0否1是 */
    ship_fare_type: number
    /** 最低价 */
    min_price: number
    /** 最高价 */
    max_price: number
    /** 是否加入购物车:0是否，1是 */
    add_cart: number
    /** 商品bannner图 */
    product_banner: any[]
    /** 商品详情 */
    content: string
    /** 销售价格 */
    price_sale: number
}

export class Westore extends Base {
    constructor(host: string) { super(host); }
    public Category = { list: (message: string): Promise<Response<string>> => { return this.post("/gw/v3/category/list", { message: message }); } };
    public Document = { previewLink: (id: number): Promise<Response<string>> => { return this.post("/gw/v3/document/previewLink", { id: id }); } };
    public Member = {
        apply: (request: app_westore_api_vo_MemberApplyRequest): Promise<Response<boolean>> => { return this.post("/gw/v3/member/apply", { request: request }); },
        applyResult: (): Promise<Response<app_westore_api_vo_MemberApplyResult>> => { return this.post("/gw/v3/member/applyResult", {}); }
    };
    public MyCustomer = { myCustomerList: (): Promise<Response<app_westore_api_vo_MyCustomerResult>> => { return this.post("/gw/v3/myCustomer/myCustomerList", {}); } };
    public Product = { list: (): Promise<Response<string>> => { return this.post("/gw/v3/product/list", {}); } };
    public WestoreInfo = {
        westoreInfo: (): Promise<Response<app_westore_api_vo_WestoreInfoResult>> => { return this.post("/gw/v3/westoreInfo/westoreInfo", {}); },
        filtratePrice: (): Promise<Response<app_westore_api_vo_PriceIntervalResult>> => { return this.post("/gw/v3/westoreInfo/filtratePrice", {}); },
        filtratePriceGoods: (request: any, offset: any, length: any): Promise<Response<app_westore_api_vo_SearchPriceGoodsResult>> => {
            return this.post("/gw/v3/westoreInfo/filtratePriceGoods", {
                request: request,
                offset: offset,
                length: length
            });
        }
    };
}